package dayu

import (
	"bytes"
	"errors"
	"fmt"
	"io/ioutil"
	"publish/pub-lib/baijia"
	"publish/pub-lib/utils"
	"github.com/astaxie/beego"
)

func (q *DayuApi) PublishArticle(cat string,tag string,article baijia.FeedArticle) error {
	da := &DArticle{}
	da.Title = article.Title
	da.Author = q.author

	for _, feed := range article.Feed {
		if feed.Type == "image" {
			urlRes, err := q.uploadImageByUrl(feed.Data)
			if err != nil {
				continue
			}
			if len(da.CoverImages) <= 0 {
				curlRes, err := q.cuttingImageByUrl(urlRes.Url)
				if err != nil {
					continue
				}
				da.CoverImages = curlRes.Url
			}
			da.Content += Imgwrapper(urlRes.Url, feed.Desc)
		}

		if feed.Type == "text" {
			da.Content += Pwrappper(feed.Data)
		}
	}

	aid, err := q.save(da)
	if err != nil {
		beego.Info(err)
		return err
	}
	if len(aid) <= 0 {
		return errors.New("大鱼发表失败：保存草稿返回aid 是空")
	}

	return q.publish(aid)
}

func (q *DayuApi) PublishGallery(cat string,tag string,article baijia.FeedArticle) error {
	gallery := &Gallery{Images: []KV{}}
	gallery.Title = article.Title

	imageIndex := 0
	for _, feed := range article.Feed {
		if feed.Type == "image" {
			req := utils.Get(feed.Data)
			byteArray, err := req.Bytes()
			if err != nil {
				return err
			}
			res, err := q.uploadImageByFile(ioutil.NopCloser(bytes.NewBuffer(byteArray)), "gallery_imgae", int64(len(byteArray)))
			if err != nil {
				fmt.Println("UploadImageByUrl|", err.Error())
				continue
			}

			if len(gallery.CoverImg) <= 0 {
				gallery.CoverImg = res.Result.Src
			}

			gallery.Images = append(gallery.Images, KV{fmt.Sprintf(`imgs[%d][url]`, imageIndex), res.Result.Url})
			gallery.Images = append(gallery.Images, KV{fmt.Sprintf(`imgs[%d][format]`, imageIndex), res.Result.Format})
			gallery.Images = append(gallery.Images, KV{fmt.Sprintf(`imgs[%d][height]`, imageIndex), res.Result.Height})
			gallery.Images = append(gallery.Images, KV{fmt.Sprintf(`imgs[%d][width]`, imageIndex), res.Result.Width})
			gallery.Images = append(gallery.Images, KV{fmt.Sprintf(`imgs[%d][phash]`, imageIndex), ""})
			gallery.Images = append(gallery.Images, KV{fmt.Sprintf(`imgs[%d][size]`, imageIndex), res.Result.Size})
			gallery.Images = append(gallery.Images, KV{fmt.Sprintf(`imgs[%d][description]`, imageIndex), feed.Desc})
			gallery.Images = append(gallery.Images, KV{fmt.Sprintf(`imgs[%d][disabled]`, imageIndex), "false"})

			imageIndex++
		}
	}
	gid, err := q.saveGallery(gallery)
	if err != nil {
		return err
	}
	return q.publishGallery(gid)
}

func (q *DayuApi) PublishVideo(cat string,tag string,article baijia.FeedArticle) error {
	return errors.New("not implement interface")
}
